package cc.rengu.redp.bizimpl.csmc.service.impl;

import cc.rengu.redp.bizimpl.csmc.common.CsmcConstant;
import cc.rengu.redp.bizimpl.csmc.domain.CClearPlanMap;
import cc.rengu.redp.bizimpl.csmc.dao.CClearPlanMapMapper;
import cc.rengu.redp.bizimpl.csmc.service.ICClearPlanMapService;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.redis.RedisService;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.Wrapper;
import java.util.Date;

/**
 * @author lizk
 */
@Service
@DS("csmc")
public class CClearPlanMapServiceImpl extends ServiceImpl<CClearPlanMapMapper, CClearPlanMap> implements ICClearPlanMapService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpSysSeqService sysSeqService;
    @Autowired
    private RedisService redisService;

    private long oprMenuId = 1;
    private String oprMenuName = "清分清算管理:清分清算方案管理";
    private long chkMenuId = 2;
    private String chkMenuName = "清分清算管理:清分清算方案管理";
    private String webNextUrl = "/admin/csmc/clearPlanMap";

    @Override
    public IPage<CClearPlanMap> findByPage(QueryRequest queryRequest, CClearPlanMap clearPlanMap) {
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);


        try {
            String instId = clearPlanMap.getInstId();
            if (Common.isBlank(instId)) {
                instId = user.getInstId();
            }
            LambdaQueryWrapper<CClearPlanMap> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(instId)) {
                queryWrapper.eq(CClearPlanMap::getInstId, instId);
            }
            if (!StringUtils.isEmpty(clearPlanMap.getPlanMapDesc())) {
                queryWrapper.like(CClearPlanMap::getPlanMapDesc, clearPlanMap.getPlanMapDesc());
            }
            Page<CClearPlanMap> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取清分清算方案管理信息失败", e);
            return null;
        }
    }

    @Override
    public void createClearPlanMap(CClearPlanMap entity) throws Exception {
        entity.setMatchKey(entity.getTransChannelIdList() + entity.getPayChannelIdList() + entity.getTxnNum()
                + entity.getCsmcBizTypeList() + entity.getReconRslt() + entity.getOtherCond1() + entity.getOtherCond2());

        String optFlag = entity.getOptFlag();

        LambdaQueryWrapper<CClearPlanMap> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CClearPlanMap::getInstId, entity.getInstId()).eq(CClearPlanMap::getMatchKey, entity.getMatchKey());
        CClearPlanMap clearPlanMap = baseMapper.selectOne(wrapper);

        //校验match_key唯一性
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            String result = generateCode();
            entity.setClearPlanId(result);
            this.redisService.del("clearPlanId");
            this.redisService.set("clearPlanId", result);
            if (null != clearPlanMap) {
                throw new RedpException("该行清分清算方案信息已重复，请修改后再点下一步！");
            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {
            String id = entity.getId();
            if (null != clearPlanMap && !clearPlanMap.getId().equals(id)) {
                throw new RedpException("该行清分清算方案信息已重复，请修改后再点下一步！");
            }
        }
        saveData(entity);
    }

    @Override
    public void updateCleaPlanMapAuditStatus(String clearPlanMapId, String type) {
        LambdaUpdateWrapper<CClearPlanMap> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CClearPlanMap::getAuditStatus, type);
        wrapper.eq(CClearPlanMap::getClearPlanId, clearPlanMapId);
        this.update(wrapper);
    }

    @Override
    public CClearPlanMap findByClearPlanId(String id) {
        LambdaQueryWrapper<CClearPlanMap> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CClearPlanMap::getId, id);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void update(CClearPlanMap cClearPlanMap) {
//        cClearPlanMap.setOprStatus(oprstatus);
//        cClearPlanMap.setAuditStatus(auditStatus);
        LambdaUpdateWrapper<CClearPlanMap> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CClearPlanMap::getInstId, cClearPlanMap.getInstId());
        updateWrapper.eq(CClearPlanMap::getMatchKey, cClearPlanMap.getMatchKey());
        this.baseMapper.update(cClearPlanMap,updateWrapper);
    }

    /**
     * 系统生成会计分录标识（格式：CS + 6位序号）
     *
     * @return
     */
    private String generateCode() {
        // 固定入参
        String common = "COMM_PARAM_CODE";
        // 会计分录标识前缀：CS
        String prefix = CsmcConstant.ClearPlanMapId_PREFIX;

        // 生成序列号
        String serialNumber = sysSeqService.updateParamValue(common, prefix, "");
        // 编码：CS + 6位顺序编号
        String result = prefix + String.format("%06d", Integer.parseInt(serialNumber));
        return result;
    }

    private void saveData(CClearPlanMap entity) throws RedpException {
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        String optFlag = entity.getOptFlag();
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");


        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            entity.setMatchKey(entity.getTransChannelIdList() + entity.getPayChannelIdList() + entity.getTxnNum()
                    + entity.getCsmcBizTypeList() + entity.getReconRslt() + entity.getOtherCond1() + entity.getOtherCond2());

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "clearPlanMap:add");

            entity.setId(entity.getId());
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
                entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                this.save(entity);
                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName, entity.getOprStatus(), entity.getAuditStatus(),
                        entity.getId(), webNextUrl, null, null, null);

            } else {
                //等第二个tab页保存后 改为正式 审批通过状态
                entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
                this.save(entity);
                CClearPlanMap entityNew = new CClearPlanMap();
                BeanUtils.copyProperties(entity, entityNew);
                entityNew.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entityNew.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName, entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "clearPlanMap:edit");

            CClearPlanMap dbclearplanmap = baseMapper.selectById(id);
            CClearPlanMap clearplanmap = new CClearPlanMap();
            CClearPlanMap clearplanmapTmp = new CClearPlanMap();
            BeanUtils.copyProperties(dbclearplanmap, clearplanmap);
            BeanUtils.copyProperties(dbclearplanmap, clearplanmapTmp);

            entity.setAuditOprId(user.getId());
            entity.setUpdateTime(lastUpddt);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                String tmpBizType = BizOprEnum.OPR_UPDATE.getType();
                clearplanmap.setAuditOprId(user.getId());
                clearplanmap.setUpdateTime(lastUpddt);
                //新增待审核的数据修改之后还是新增待审核
                if (!BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType().equals(clearplanmap.getAuditStatus())) {
                    clearplanmap.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_NOTCOMMIT.getType());
                    entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_NOTCOMMIT.getType());
                } else {
                    tmpBizType = BizOprEnum.OPR_ADD.getType();
                }
                this.saveOrUpdate(clearplanmap);
                BeanUtils.copyProperties(entity, clearplanmapTmp);
                bizTmpService.saveBizTmp(clearplanmapTmp, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName, entity.getOprStatus(), entity.getAuditStatus(),
                        entity.getId(), webNextUrl, null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_NOTCOMMIT.getType());

                BeanUtils.copyProperties(entity, clearplanmap);
                this.saveOrUpdate(clearplanmap);

                CClearPlanMap entityNew = new CClearPlanMap();
                BeanUtils.copyProperties(clearplanmap, entityNew);
                entityNew.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entityNew.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());

                bizHisService.saveBizHisNew(entityNew, dbclearplanmap, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName, clearplanmap.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            CClearPlanMap clearplanmap = baseMapper.selectById(id);
            //备份正式表数据
            CClearPlanMap clearplanmapOld = new CClearPlanMap();
            BeanUtils.copyProperties(clearplanmap, clearplanmapOld);
            if (Common.isBlank(clearplanmap)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "清分清算方案管理:停用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    clearplanmap.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_NOTCOMMIT.getType());
                    entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                } else {
                    clearplanmap.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_NOTCOMMIT.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "清分清算方案管理:启用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    clearplanmap.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_NOTCOMMIT.getType());
                    entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                } else {
                    clearplanmap.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_NOTCOMMIT.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "清分清算方案管理:注销");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    clearplanmap.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_NOTCOMMIT.getType());
                    entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                } else {
                    clearplanmap.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_NOTCOMMIT.getType());
                }
            }
            clearplanmap.setAuditOprId(user.getId());
            clearplanmap.setUpdateTime(lastUpddt);
            this.saveOrUpdate(clearplanmap);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {

                bizTmpService.saveBizTmp(clearplanmap, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName, entity.getOprStatus(), clearplanmap.getAuditStatus(),
                        entity.getId(), webNextUrl, null, null, null);

            } else {
                bizHisService.saveBizHisNew(clearplanmap, clearplanmapOld, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName, clearplanmap.getId(), null, null, null);


            }
        }
    }
}
